package contactmanager;

import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.util.*;

public class ContactFileDecryptor
{
    private String password;
    private String DecryptMode;

    public ContactFileDecryptor(String _password)
    {
        password = _password;
        DecryptMode = "PBEWithMD5AndDES";
    }

    public byte[] Decrypt(String cipherfilename)
    {
        try
        {
            FileInputStream cipherfile =
                new FileInputStream(cipherfilename);
            ByteArrayOutputStream plaintext =
                new ByteArrayOutputStream();
            PBEKeySpec keySpec =
                new PBEKeySpec(password.toCharArray());
            SecretKeyFactory skf =
                SecretKeyFactory.getInstance(DecryptMode);
            SecretKey sk = skf.generateSecret(keySpec);

            byte[] salt = new byte[8];
            cipherfile.read(salt);
            int iterations = 100;

            PBEParameterSpec ps =
                new PBEParameterSpec(salt, iterations);
            
            Cipher cipher = Cipher.getInstance(DecryptMode);
            cipher.init(Cipher.DECRYPT_MODE, sk, ps);

            byte[] input = new byte[64];
            int bytesRead;
            while((bytesRead = cipherfile.read(input)) != -1)
            {
                byte[] output = cipher.update(input, 0, bytesRead);
                if (output != null)
                   plaintext.write(output);
            }

            byte[] output = cipher.doFinal();
            if (output != null)
                plaintext.write(output);
             cipherfile.close();
             //plaintext.flush();
             return plaintext.toByteArray();
        }
        catch (Exception e)
        {
            System.err.println("Error while decrypting file: "
                                + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
}
